#region Imported Namespaces
using System;
using System.Collections; 
using InsightPolicy = PHSRAG.Insight21.Policy;
using InsightHumans = PHSRAG.Insight21.Humans;
using InsightUtility = PHSRAG.Utility;
using WorFlowInterface = Workflow.NET.Engine.Interfaces;
using WorkFlowEngine = Workflow.NET.Engine;
using Workflow.NET;
using System.Threading;
#endregion

namespace PHSRAG.Insight21.InsightWorkFlow
{
	#region Class GetWorkflowType
	/// <summary>
	/// This is a Skelta workflow custom action class. This class is used to get the Protocol Process Type. The actual flow of Workflow item
	/// depends on the return value of this action.
	/// IActionRun is Skelta interface to implement custom actions. 
	/// Actions.xml of particular application needs to be configured so that this action
	/// becomes accesible from Skelta Workflow Manager control under List of Actions -> Custom Actions. 
	/// This action does not take any parameter. 
	/// </summary>
	public class GetWorkflowType:WorkFlowEngine.Interfaces.IActionRun		
	{		
		public const string InitialReview = "PPTYPE_IR";
		public const string Amendment = "PPTYPE_AM";
		public const string AdverseEvent = "PPTYPE_AE";
		public const string ContinuingReview = "PPTYPE_CR";
		public const string OtherEvent = "PPTYPE_OE";

		private const string questionnaireName = "InitialReview";
		/// <summary>
		/// Default constructor
		/// </summary>
		public GetWorkflowType()
		{
			
		}
		/// <summary>
		/// This custom action gets the Prtocol Process Type. This method is used from Parent workflow. This determines which sub-workflow the item goes.		
		/// </summary>
		/// <param name="executionId">Workflow execution Id - a unique id used for each workflow item</param>
		/// <param name="executionDetailsId">Execution detail Id - Id used for execution detail table</param>
		/// <param name="currentContext">Context class which encapsulates all the information about the executing Workflow.</param>
		/// <param name="currentAction">Current Workflow action</param>
		/// <param name="inlinkOutput">Output in string format which has come from the step before this step</param>
		/// <param name="retry">Boolean retry variable</param>
		/// <param name="output">Output value which is used by Skelta Workflow manager to takce certain path in the process.</param>
		/// <returns>The result of an action execution. Either execution is complete or action is in sleep mode.  </returns>
		public  WorFlowInterface.ActionResult Run(int executionId,int executionDetailsId,WorkFlowEngine.Context currentContext,Action currentAction,string inlinkOutput,bool retry,out string output)
		{	
			output=null;	
			Log logger = currentContext.log;
			HumansWorkFlow humansWF = new HumansWorkFlow(new InsightPolicy.NullCachePolicy());

			try
			{
                //System.Diagnostics.Debugger.Launch();							
               	Humans.ProtocolProcess protocolProcess=null;
				Humans.Protocol protocol=null;
				string processType;
				int protocolProcessId,protocolId;
				ArrayList answerList =null;
				protocolProcessId=Int32.Parse(currentContext.Contents["ppid"].Value.ToString());
				protocolId=Int32.Parse(currentContext.Contents["protocolid"].Value.ToString());

                object insightApplicationName = currentContext.Contents["insightApplicationName"];
                HumansWorkFlow.InsightApplicationName = (null == insightApplicationName) ? string.Empty : ((Content)insightApplicationName).Value.ToString();

                //HumansWorkFlow.InsightApplicationName = currentContext.Contents["insightApplicationName"].Value.ToString();
                Thread.SetData(Thread.GetNamedDataSlot("Connections"), HumansWorkFlow.Connections);
				
				if (protocolProcessId !=0)
				{
					protocolProcess=humansWF.GetProtocolProcess(protocolProcessId);
					processType=protocolProcess.Type;
									
					if (processType !=null)
					{
						// if it's a resubmit, get the Resubmit WF and sent it through here.
						if ( protocolProcess.Resubmission )
						{
							output="RESUB";
						}
						else
						{
							switch (processType)
							{
								case InitialReview:
									if(protocolId !=0)
									{
										protocol=humansWF.GetProtocol(protocolId);
										if (protocol.ProtocolTypeCode==Humans.Constants.NewProtocolType.EmergencyApp)
										{
											output="EMG";
										}
										else
										{
											answerList=humansWF.GetQIAnsByQName(protocolProcess,"InitialReview","Interaction");
											if(answerList !=null && answerList.Count>0)
												output=((((FormsManagement.Answer)answerList[0]).Value=="Yes")? "INT_IR":"NINT_IR");
										}
									}
									break;								
								case Amendment:
									output = "AME";
									break;
								case ContinuingReview:
									output = "CR";
									break;
								default:
									if(processType==AdverseEvent ||processType==OtherEvent)
									{
										output = "ADV";
									}
									break;
							}
						}
					}
				}
				
			}
			catch (Exception ex)
			{				
				logger.LogMessage(ReasonConst.Error, "Unable to get Workflow type in GetWorkflowType.Run() " + ex.ToString());  				
				output = "Failure";									
			}	
			finally
			{
				humansWF.Dispose();
			}
			currentContext.Variables["workflowType"].Value=output;
			currentContext.SaveVariables();
			return WorFlowInterface.ActionResult.Completed;  			
		}
		
		/// <summary>
		/// Gets the web control to be displayed in the activity list for this action. No user interface is implemented for
		/// this action. So it returns null.
		/// </summary>
		/// <returns>IActivityWebUIHandler - Interface that allows an object to implement a custom document view Control.</returns>
		public virtual Workflow.NET.Interfaces.IActivityWebUIHandler GetActivityWebUIHandler()
		{
			return null;
		} 

	}
	#endregion
}

